"""
通义千问客户端
封装通义千问API调用
"""

import os
import logging
from typing import List, Dict, Any
import requests
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

logger = logging.getLogger(__name__)

class QWENClient:
    """通义千问API客户端"""
    
    def __init__(self):
        """初始化客户端"""
        self.api_key = os.getenv('QWEN_API_KEY')
        self.base_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
        
        if not self.api_key:
            raise ValueError("QWEN_API_KEY 环境变量未设置")
        
        logger.info("通义千问客户端初始化成功")
    
    def chat_completion(self, messages: List[Dict[str, str]], model: str = "qwen-max") -> str:
        """
        调用通义千问Chat API
        
        Args:
            messages: 消息列表
            model: 模型名称
            
        Returns:
            AI回复内容
        """
        try:
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }
            
            payload = {
                "model": model,
                "input": {
                    "messages": messages
                },
                "parameters": {
                    "temperature": 0.7,
                    "max_tokens": 1000
                }
            }
            
            response = requests.post(self.base_url, json=payload, headers=headers)
            response.raise_for_status()
            return response.json()["output"]["text"]
        except Exception as e:
            logger.error(f"通义千问API调用失败: {str(e)}")
            raise
    
    def analyze_resume_skills(self, resume_content: str) -> Dict[str, Any]:
        """
        分析简历技能
        
        Args:
            resume_content: 简历内容
            
        Returns:
            技能分析结果
        """
        prompt = f"""
        请分析以下简历内容，提取并分析技能信息。
        
        简历内容：
        {resume_content}
        
        请按以下格式返回JSON：
        {{
            "technical_skills": ["技能1", "技能2", ...],
            "soft_skills": ["软技能1", "软技能2", ...],
            "skill_level": "初级/中级/高级",
            "strengths": ["优势1", "优势2", ...],
            "improvement_suggestions": ["建议1", "建议2", ...]
        }}
        """
        
        messages = [
            {"role": "system", "content": "你是一个专业的简历分析师，擅长提取和分析技能信息。"},
            {"role": "user", "content": prompt}
        ]
        
        try:
            response = self.chat_completion(messages)
            import json
            return json.loads(response)
        except Exception as e:
            logger.error(f"技能分析失败: {str(e)}")
            return {
                "technical_skills": [],
                "soft_skills": [],
                "skill_level": "未知",
                "strengths": [],
                "improvement_suggestions": []
            }
    
    def generate_interview_advice(self, resume_content: str) -> List[Dict[str, str]]:
        """
        生成面试建议
        
        Args:
            resume_content: 简历内容
            
        Returns:
            面试建议列表
        """
        prompt = f"""
        请根据以下简历内容，生成个性化的面试建议。
        
        简历内容：
        {resume_content}
        
        请从以下角度提供建议：
        1. 技术面试准备
        2. 项目经验展示
        3. 行为面试技巧
        4. 简历优化建议
        
        请按以下格式返回JSON：
        [
            {{"title": "建议标题", "content": "建议内容"}},
            ...
        ]
        """
        
        messages = [
            {"role": "system", "content": "你是一个资深的面试指导专家，擅长提供个性化的面试建议。"},
            {"role": "user", "content": prompt}
        ]
        
        try:
            response = self.chat_completion(messages)
            import json
            return json.loads(response)
        except Exception as e:
            logger.error(f"面试建议生成失败: {str(e)}")
            return [
                {"title": "通用建议", "content": "建议准备STAR法则回答行为面试问题，突出你的能力和成果。"}
            ]
